const db = require('../mongod/db');
const getHash = require('../mongod/md').getHash;
const jwt = require('jsonwebtoken');
const moment = require('moment');

const userinfo = 'userinfo'; // 用户集合名

function errMongo(res) {
  res.send({
    isok: false,
    msg: '数据库错误！请联系后端！',
  });
  return;
}

// 用户登录部分内容
function fn(result, req, res) {
  let token = jwt.sign({ name: req.body.username }, 'Family', {
    expiresIn: 60 * 60,
  });
  if (result.length === 0) {
    res.send({
      isok: false,
      code: 1,
      info: '该账号不存在',
    });
    return;
  } else {
    res.send({
      isok: true,
      code: 0,
      info: '登录成功',
      token,
      userinfo: result[0],
    });
    return;
  }
}

// 账密登录
function login(req, res) {
  const body = req.body;
  let username = body.username;
  let password = getHash(body.password);
  if (body.isok) {
    db.find(userinfo, { username, password }, (err, result) => {
      if (err) {
        errMongo(res);
        return;
      }
      fn(result, req, res);
    });
  } else {
    db.find(userinfo, { phone: username, password }, (err, result) => {
      if (err) {
        errMongo(res);
        return;
      }
      fn(result, req, res);
    });
  }
}

// ID Card登录
function login1(req, res) {
  const body = req.body;
  let query = {
    username: body.username,
    idcard: body.idcard,
  };
  db.find(userinfo, query, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    fn(result, req, res);
  });
}

/**
 * 用户增
 * @param { * } req
 * @param { * } res
 */
function addUser(req, res) {
  let query = req.body;
  db.find(userinfo, { idcard: query.idcard }, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    if (result.length === 0) {
      // 表示尚未有此用户注册
      if (!query.username || !query.password || !query.idcard || !query.phone) {
        let json = {
          isok: false,
          code: 4,
          info: '缺少必填参数',
        };
        res.send(json);
        return;
      }

      // eslint-disable-next-line
      t2 = {
        userId:
          moment(new Date()).format('YYYYMMDD') +
          Math.round(Math.random() * 899 + 100),
        username: query.username,
        idcard: query.idcard,
        phone: query.phone,
        password: getHash(query.password), // 加密
        createTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        updateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        check: false,
      };

      // eslint-disable-next-line
      db.insert(userinfo, t2, (err, result) => {
        if (err) {
          errMongo(err);
          return;
        }
        let json = {
          isok: true,
          code: 200,
          info: '添加成功',
        };

        // eslint-disable-next-line
        let json1 = {
          // 建议以后这样写
          status: 0, // 0 成功  1   2
          code: 1111,
          message: '操作成功',
          statusText: 'OK',
          result: {
            // 登录时间
            loginTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            username: '',
            uid: '',
          },
        };
        res.send(json);
        return;
      });
    } else {
      // 此用户已存在
      let json = {
        isok: false,
        code: 2,
        info: '此账号已存在',
      };
      res.send(json);
      return;
    }
  });
}

/**
 * 用户查
 * @param { * } req
 * @param { * } res
 */
function findUser(req, res) {
  let query = req.query;
  db.find(userinfo, query, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    result.forEach((ele) => {
      // 删除默认_id
      delete ele._id;
    });
    result.sort((a, b) => {
      // 根据创建时间排序
      let t1 = new Date(a.createTime);
      let t2 = new Date(b.createTime);
      return t2.getTime() - t1.getTime();
    });
    let json = {
      isok: true,
      code: 200,
      info: '查询成功',
      data: result,
    };
    res.send(json);
    return;
  });
}

/**
 * 用户改【通过用户ID更改信息】
 * @param { * } req
 * @param { * } res
 */
function updateUser(req, res) {
  let query = req.query;
  query['updateTime'] = moment(new Date()).format('YYYY-MM-DD HH:mm:ss'); // 重新赋值
  query['password'] = getHash(query.password);
  let condition = {
    // 条件
    userId: query.userId,
  };
  let newValue = {
    $set: { ...query },
  };
  // 方法，集合名，条件，更新内容
  // eslint-disable-next-line
  db.update('updateOne', userinfo, condition, newValue, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 200,
      info: '更新成功',
    };

    res.send(json);
    return;
  });
}

/**
 * 用户删
 * @param { * } req
 * @param { * } res
 */
function deleteUser(req, res) {
  let query = req.query;

  // eslint-disable-next-line
  db.deleteInfo('deleteOne', userinfo, query, (err, result) => {
    if (err) {
      errMongo(res);
      return;
    }
    let json = {
      isok: true,
      code: 0,
      info: '删除成功',
    };
    res.send(json);
    return;
  });
}

module.exports = {
  addUser,
  findUser,
  updateUser,
  deleteUser,
  login,
  login1,
};
